#include "resourcemanager.h"
#include "config/config.h"
#include "config/configgroup.h"

#include <iostream>
#include <string>

#include <stdio.h>
#include <stdlib.h>

ResourceManager* ResourceManager::m_self = 0;

ResourceManager::ResourceManager()
{
    m_self = this;
    string resourcesPath = "resources.bin";
    restoreProperties(Config(resourcesPath, "r")["Resources"]);
    
    #ifdef WIN32
        addResource("home", "");
    #else
        addResource("home", string(getenv(getResource("home").c_str())) + '/');
    #endif
}

ResourceManager::~ResourceManager()
{
    m_self = 0;
}

ResourceManager& ResourceManager::self()
{
    if(m_self == 0)
        new ResourceManager();
    
    return *m_self;
}

bool ResourceManager::exists()
{
	return m_self!=0;
}

void ResourceManager::addResource(const string& name, const string& resource)
{
    m_resources[name] = resource;
}

string ResourceManager::getResource(const string& name)
{
    map<string, string>::iterator it =  m_resources.find(name);
    if(it == m_resources.end())
        return "";
    else
        return it->second;
}

bool ResourceManager::hasResource(const string& name)
{
    map<string, string>::iterator it =  m_resources.find(name);
    return it != m_resources.end();
}

void ResourceManager::removeResource(const string& name)
{
    map<string, string>::iterator it =  m_resources.find(name);
    if(it == m_resources.end())
        m_resources.erase(it);
}

void ResourceManager::saveProperties(ConfigGroup& groupConfig)
{
    map<string, string>::iterator it = m_resources.begin();
    for(; it != m_resources.end(); it++)
    {
        groupConfig.writeEntry(it->first, it->second);
    }
}

void ResourceManager::restoreProperties(ConfigGroup& groupConfig)
{
    list<string> tmpList = groupConfig.keyList();
    list<string>::iterator it = tmpList.begin();
    string key, value;
    
    for(; it != tmpList.end(); it++)
    {
        key = *it;
        value = groupConfig.readEntry(key, "");
        if(value != "")
            m_resources[key] = value;
    }
}

string ResourceManager::operator[](const string& name)
{
    return getResource(name);
}
